package com.pvj.myaccount.ui.home

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.pvj.myaccount.AddActivity
import com.pvj.myaccount.KeyConfig
import com.pvj.myaccount.R
import com.pvj.myaccount.adapter.RecyclerViewAdapter
import com.pvj.myaccount.databinding.FragmentHomeBinding
import com.pvj.myaccount.room.DbHelper
import com.pvj.myaccount.room.entity.Cost
import com.pvj.myaccount.room.entity.MonthCost
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Date


class HomeFragment : Fragment(), RecyclerViewAdapter.OnItemClickListener {

    private var _binding: FragmentHomeBinding? = null
    private lateinit var recyclerViewAdapter: RecyclerViewAdapter
    private lateinit var homeViewModel: HomeViewModel

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        homeViewModel = ViewModelProvider(this)[HomeViewModel::class.java]
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val root: View = binding.root

        this.context?.let { recyclerViewAdapter = RecyclerViewAdapter() }
        recyclerViewAdapter.setOnItemClickListener(this)
        _binding!!.recyclerView.layoutManager = LinearLayoutManager(activity) // 用于线性布局
        _binding!!.recyclerView.adapter = recyclerViewAdapter

        //添加自定义分割线：可自定义分割线高度和颜色
        _binding!!.recyclerView.addItemDecoration(
            RecycleViewDivider(
                activity,
                LinearLayoutManager.HORIZONTAL,
                20,
                resources.getColor(R.color.app_bg)
            )
        )
        //  this.loadData()
        Log.d("HomeFragment", "---------------------------------");

        homeViewModel.costs.observe(viewLifecycleOwner) {
            // 更新UI
            updateUI(it)
        }
        return root
    }

    override fun onResume() {
        super.onResume()
        homeViewModel.loadTodayData()
    }

    private fun loadData() {
        scope.launch {
            val data = withContext(Dispatchers.IO) {
                val date = Date()
                val timeMillis = date.time // 获取Unix时间戳（毫秒）
                DbHelper.INSTANCE?.costDao()
                    ?.insert(Cost("henry0", 1.0, "测试",timeMillis)) // 假设这是一个Room的DAO调用
                DbHelper.INSTANCE?.costDao()
                    ?.insert(Cost("henry99", 99.0, "测试", timeMillis)) // 假设这是一个Room的DAO调用

                //查看全部数据
                val list = DbHelper.INSTANCE?.costDao()?.getAll()
                Log.d("HomeFragment", "all = " + list.toString());
            }
            // 在这里更新UI线程
            withContext(Dispatchers.Main) {
                homeViewModel.loadTodayData()
                Log.d("HomeFragment", "--------------------------------- updateUI");
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateUI(data: List<Cost>?) {
        // 更新列表、文本视图或其他UI组件
        recyclerViewAdapter.submitList(data)
        var total = 0.0
        if (data != null) {
            for (cost in data) {
              total += cost.money
            }
        }
        binding.totalTv.text = "Total:$total"
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onUpdate(v: Cost) {
        startAddActivity(KeyConfig.TYPE_COST,v)
    }

    override fun onDelete(v: Cost) {
        scope.launch {
            withContext(Dispatchers.IO) {
                homeViewModel.delete(v)
            }
            // 在这里更新UI线程
            withContext(Dispatchers.Main) {
                homeViewModel.loadTodayData()
            }
        }
    }

    private fun startAddActivity(type: Int,data: Cost) {
        val intent = Intent(activity, AddActivity::class.java)
        intent.putExtra(KeyConfig.KEY_TYPE, type)
        intent.putExtra(KeyConfig.KEY_DATA, data)
        startActivity(intent)
    }
}